package master;

import java.util.HashMap;
import java.util.Map;

/**
 * 根据中序与后序遍历序列构建二叉树
 *
 * @author chenyw
 * @date 2022/8/5 12:50
 */
public class M106buildTree {
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    //后序遍历就是谦虚遍历中先遍历右子树在遍历左子树的reverse
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        int n = inorder.length;

        for (int i = 0; i < n; i++) {
            map.put(inorder[i], i);
        }
        return dfs(inorder, postorder, 0, n - 1, 0, n - 1);
    }

    private TreeNode dfs(int[] inorder, int[] postorder, int in_left, int in_right, int post_left, int post_right) {
        if (in_left > in_right) {
            return null;
        }
        int root_index = map.get(postorder[post_right]);
//        int right_size = in_right - root_index;
        int left_size = root_index - in_left;
        TreeNode root = new TreeNode(postorder[post_right]);
//        root.left = dfs(inorder, postorder, in_left, root_index - 1,post_left, post_right - right_size - 1);
//        root.right = dfs(inorder, postorder, root_index + 1, in_right, post_right - right_size, post_right - 1);
        root.left = dfs(inorder, postorder, in_left, root_index - 1, post_left, post_left +left_size - 1);
        root.right = dfs(inorder, postorder, root_index + 1, in_right, post_left + left_size, post_right - 1);

        return root;
    }

}
